const app = getApp()

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    nickName: ''
  },
  nickNameBind(e){

  },
  onLoad() {
    var userInfo = app.globalData.userInfo;
    if(userInfo != null && userInfo.cIcon != null){
      this.setData({
        avatarUrl:userInfo.cIcon
      })
    }
    if(userInfo != null && userInfo.cNickName != null){
      this.setData({
        nickName:userInfo.cNickName
      })
    }
  },
  onChooseAvatar(e) {
    var that = this;
    // 设置头像
    const { avatarUrl } = e.detail 
    wx.showLoading({
      title: '图片上传中',
      mask:'true'
    })
    wx.uploadFile({
      // 上传至服务器地址
      url:app.globalData.baseUrl + 'api/file/imgUpload',
      // 文件路径
      filePath: avatarUrl,
      // 名称
      name: 'file',
      success (res){
        const data = JSON.parse(res.data)
        that.setData({
          avatarUrl:data.data.url
        })
      },
      fail(res){
      },
      complete(){
        wx.hideLoading();
      }
    })
  },
  comit(){
    var that = this;
    if(that.data.nickName == null || that.data.nickName==''){
      wx.showToast({
        title: '请输入昵称',
        icon:'none'
      })
      return;
    }
    wx.request({
      url: app.globalData.baseUrl + 'api/wx/v1/updateUserInfo',
      method:'POST',
      data:{
        "cOpenid":app.globalData.openid,
        "cIcon":that.data.avatarUrl,
        "cNickName":that.data.nickName
      },
      success(res){
        app.globalData.userInfo = {
          "cIcon":that.data.avatarUrl,
          "cNickName":that.data.nickName
        }
        wx.setStorageSync('userInfo', that.data.userInfo)
        // 返回上一页
        wx.navigateBack();
      },
      fail(e){
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  }
})
